<?php
namespace App\Services\Fund\Withdraw;
use App\Services\Fund\FundAccount\FundAccountLogic;
use App\Services\UCenter\UCenter\UCenterLogic;
use App\Services\User\Token\TokenLogic;
use App\Models\Cargo\WayBill;
use App\Models\Fund\FundOptionLog;
use App\Models\Fund\Withdraw;
use App\Models\Fund\FundAccount;
use App\Models\User\User;
use App\Models\UCenter\Payment;
use App\Models\UCenter\Complain;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;
use App\Services\User\Traits\Password;

class WithdrawLogic
{
    use Password;
    /*我的 - 申请提现*/
    public function applyDrawwith($data): array
    {
        $token = $data['token'];
        unset($data['token']);
        //验证用户支付密码
        $info = User::select('pay_password','pay_salt')
            ->where(['id' => $data['user_id']])
            ->first()
            ->toArray();
        if(!$info){
            return verify_err(null, '没有相关用户信息');
        }else if($info['pay_password'] === ''){
            return verify_err(null, '您还没有设置支付密码');
        }
        // 验证支付密码
        $check = $this->_checkPayPassword($data['pay_password'], $info);
        if(!$check){
            return verify_err(null, '支付密码错误');
        }
        DB::beginTransaction();
        try{
            // 获取银行卡信息
            $card_info = Payment::where('id', $data['card_id'])->get()->toArray();
            //申请提现记录表中添加记录 + 冻结该用户资金
            $data = pick_array($data, ['card_id', 'money', 'user_id', 'user_info']);
            $data['user_info'] = json_encode($data['user_info']);
            $data['card_info'] = json_encode($card_info);
            $data['review_info'] = '{}';
            $data['type'] = $card_info[0]['type'];
            $id = Withdraw::insertGetId($data);
            $freezeData['obj_id'] = $id;
            $freezeData['user_id'] = $data['user_id'];
            $freezeData['opposite_id'] = SYSTEM_ID;
            $freezeData['money'] = $data['money'];
            $freezeData['update_ip'] = Request::getClientIp();
            $freezeData['user_info'] = json_encode($data['user_info']);
            $freezeData['opposite_info'] = isset($data['opposite_info']) ? $data['opposite_info'] : json_encode(['name'=>'system']);
            $freezeData['type'] = 'withdraw';
            $freezeData['freeze_counts'] = 1;
            $freezeRes = (new FundAccountLogic())->freeze($freezeData);
            if($freezeRes['status'] != SUCCESS_STATUS){
                return $freezeRes;
            }
            //更新redis中的用户資金信息 fund_etc
            $fund = FundAccount::where('user_id','=',$data['user_id'])->first()->toArray();
            $tokenObj = new TokenLogic();
            $oldInfo = $tokenObj->hGetAll($token);
            $arr1 = json_decode($oldInfo['res']['fund_etc'],true);
            $userInfo['fund_etc'] = json_encode(array_replace($arr1,$fund));
            $updateTokenRes = $tokenObj->hMset(['token'=>$token, 'arr'=>$userInfo]);
            // 提交事务
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return server_err(null, '数据库异常:' . $e->getMessage());
        }
        return auto_return($freezeRes);

    }

    // 验证用户传入的支付密码是否正确
/*    private function _checkPayPassword(string $inputPassword, string $paySalt): bool
    {
        $pay_password = md5($inputPassword . 'thinklev_pay' . $paySalt);
        return $pay_password === $inputPassword;
    }*/

    /*我的 - 申请提现列表（分页）*/
    public function withdrawList($data): array
    {
        $res = Withdraw::where('user_id','=',$data['user_id'])->orderBy('id', 'desc')->paginate(10)->toArray();
        return auto_return($res, '已找到提现列表数据', '没有提现列表数据');
    }

    /*司机/企业的收入统计 今日收入 当月累计收入 总收入 余额 保证金 待收款 罚金*/
    public function earnings($data): array
    {
        $res = [];
        //总收入 保证金 余额 今日收入 当月累计收入
        $fund = FundAccount::where('user_id','=',$data['user_id'])->first();
        $res['income'] = $fund->income;
        $res['deposit'] = $fund->deposit;
        $res['cash'] = $fund->cash;
        $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
        $endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        $beginThismonth=mktime(0,0,0,date('m'),1,date('Y'));
        $endThismonth=mktime(23,59,59,date('m'),date('t'),date('Y'));
        $today = [$beginToday,$endToday];
        $month = [$beginThismonth,$endThismonth];
        $res['today_income'] = FundOptionLog::where('user_id','=',$data['user_id'])->where('type','=','payment')->whereBetween('create_time',$today)->sum('money');
        $res['month_income'] = FundOptionLog::where('user_id','=',$data['user_id'])->where('type','=','payment')->whereBetween('create_time',$month)->sum('money');
        //司机个人
        if (in_array('164',explode(',',$data['role_ids']))) {
            //待收款(1.无公司id 不是委托单 2.有公司id 是委托单)
            $_where['driver_id'] = (int)$data['user_id'];
            $_where['company_id'] = 0;
            $_where['entrust_status'] = 0;
            $accountPayable1 = WayBill::where($_where)->whereIn('status',[2,3])->sum('price');
            $accountPayable2 = WayBill::where('driver_id','=',$data['user_id'])->where('company_id','<>',0)->where('entrust_status','=',1)->whereIn('status',[2,3])->sum('price');
            $res['accountPayable'] = bcadd($accountPayable1,$accountPayable2);
            //罚金
            $res['penalty'] = WayBill::join('complain', 'waybills.id', '=', 'complain.waybill_id')
                ->select('waybills.driver_id', 'complain.*')
                ->where('waybills.driver_id', '=', $data['user_id'])
                ->where('complain.reply_status', '=', 1)
                ->where('complain.status', '=', 1)
                ->sum('complain.driver_cost');
        }elseif (in_array('166',explode(',',$data['role_ids']))) {
            //企业
            //待收款(有公司id 不是委托单)
            $_where['company_id'] = $data['user_id'];
            $_where['entrust_status'] = 0;
            $res['accountPayable'] = WayBill::where($_where)->whereIn('status',[2,3])->sum('price');
            //罚金 0
            $res['penalty'] = 0;
        }
        return auto_return($res, '已找到车主/企业收入统计', '没有收入统计数据');

    }

    /*车主端七日收入统计 当月收入统计*/
    public function driverIncomeStatistic($data): array
    {
        $sumArray1 = [];
        $sumArray2 = [];
        $j = 0;$k = 1;
        // 七日收入
        for($i=7;$i>=1;$i--){
            $daystr1=date('Y-m-d', strtotime("-$i day"));
            $res1=DB::table('fund_option_log')->where('user_id','=',$data['user_id'])->whereRaw("create_time>=unix_timestamp('$daystr1 00:00:00')")->whereRaw("create_time<=unix_timestamp('$daystr1 23:59:59')")->where('type','=','payment')->sum('money');
            $sumArray1[$j]['sales']=$res1;
            $sumArray1[$j]['day']=$k;
            $j++;$k++;
        }
/*        // 当月收入
        for($i=30;$i>=0;$i--){
            $daystr2=date('Y-m-d', strtotime("-$i day"));
            $searchstr2="TO_DAYS(from_unixtime(create_time,'%Y-%m-%d'))=TO_DAYS('".$daystr2."')";
            $res2=FundOptionLog::where($searchstr2)->where('user_id','=',$data['user_id'])->where('type','=','payment')->sum('money');
            $sumArray2[]=$res2;
        }*/
        $sumArray = [
            '七日收入'=>$sumArray1,
            //'当月收入'=>$sumArray2
        ];

        return auto_return($sumArray, '找到数据', '没有数据');

    }

    /*司机/企业的待收货运单*/
    public function dueInWaybills($data): array
    {
        $res = [];
        //司机个人
        if (in_array('164',explode(',',$data['role_ids']))) {
            //待收款(1.无公司id 不是委托单 2.有公司id 是委托单)
            $_where['waybills.driver_id'] = (int)$data['user_id'];
            $_where['waybills.company_id'] = 0;
            $_where['waybills.entrust_status'] = 0;
            $accountPayable1 = WayBill::join('user', 'user.id', '=', 'waybills.owner_id')->where($_where)->whereIn('waybills.status',[2,3])->select('waybills.*', 'user.real_name', 'user.head_portrait')->get()->toArray();
            $accountPayable2 = WayBill::join('user', 'user.id', '=', 'waybills.owner_id')->where('waybills.driver_id','=',$data['user_id'])->where('waybills.company_id','<>',0)->where('waybills.entrust_status','=',1)->whereIn('waybills.status',[2,3]) ->select('waybills.*', 'user.real_name', 'user.head_portrait')->get()->toArray();
            $res = array_merge($accountPayable1,$accountPayable2);
        }elseif (in_array('166',explode(',',$data['role_ids']))) {
            //企业
            //待收款(有公司id 不是委托单)
            $_where['waybills.company_id'] = $data['user_id'];
            $_where['waybills.entrust_status'] = 0;
            $res = WayBill::join('user', 'user.id', '=', 'waybills.owner_id')->where($_where)->whereIn('waybills.status',[2,3])->select('waybills.*', 'user.real_name', 'user.head_portrait')->paginate(10);
        }
        return auto_return($res, '已找到车主/企业待收货运单', '没有待收货运单数据');

    }

    /*司机的罚单列表*/
    public function penalty($data): array
    {
        $res = Complain::join('waybills', 'waybills.id', '=', 'complain.waybill_id')
            ->select('waybills.*', 'complain.remark', 'complain.driver_cost', 'complain.reply_status', 'complain.reply', 'complain.result', 'complain.status as complain_status')
            ->where('waybills.driver_id', '=', $data['user_id'])
            ->where('complain.reply_status', '=',1)
            ->paginate(10);
        return auto_return($res, '找到罚单数据', '没有罚单数据');
    }

    /*司机 的保证金列表*/
    public function margin($data): array
    {
        $res = Waybill::join('fund_option_log', 'waybills.id', '=', 'fund_option_log.waybill_id')
            ->select('waybills.number', 'waybills.start_addr', 'waybills.created_at', 'waybills.end_addr', 'waybills.type', 'waybills.weight', 'fund_option_log.waybill_id', 'fund_option_log.create_time', 'fund_option_log.remark', 'fund_option_log.money')
            ->where('waybills.driver_id', '=', $data['user_id'])
            ->where('fund_option_log.user_id', '=', $data['user_id'])
            ->where('fund_option_log.type', '=','deposit')
            ->paginate(10);
/*        //保证金总数
        $fund = FundAccount::where('user_id','=',$data['user_id'])->first();
        $res['deposit'] = $fund->deposit;*/
        return auto_return($res, '找到保证金数据', '没有保证金数据');
    }

    //货主 冻结中资金 保证金 余额
    public function shipperMoney($data): array
    {
        $res = FundAccount::where('user_id','=',$data['user_id'])->first();
        return auto_return($res, '已找到货主资金数据', '没有货主资金数据');
    }


    /*货主 的保证金列表 余额明細 凍結資金明細 */
    public function shipperMargin($data): array
    {
        $res = Waybill::join('fund_option_log', 'waybills.id', '=', 'fund_option_log.waybill_id')
            ->select('waybills.number', 'waybills.start_addr', 'waybills.created_at', 'waybills.end_addr', 'waybills.type', 'waybills.weight', 'fund_option_log.waybill_id', 'fund_option_log.create_time', 'fund_option_log.remark', 'fund_option_log.money')
            ->where('waybills.owner_id', '=', $data['user_id'])
            ->where('fund_option_log.user_id', '=', $data['user_id'])
            ->where('fund_option_log.type', '=',$data['type'])
            ->paginate(10);
/*        //保证金总数
        $fund = FundAccount::where('user_id','=',$data['user_id'])->first();
        $res['deposit'] = $fund->deposit;
        $res['cash'] = $fund->cash;
        $res['freeze'] = $fund->freeze;*/
        return auto_return($res, '找到资金列表数据', '没有资金列表数据');
    }

    /*货主 待收货运单*/
    public function shipperDueIn($data): array
    {
            $_where['waybills.owner_id'] = (int)$data['user_id'];
            $res = WayBill::join('user', 'user.id', '=', 'waybills.driver_id')->where($_where)->whereIn('waybills.status',[2,3])->select('waybills.*', 'user.real_name', 'user.head_portrait')->paginate(10);;
        return auto_return($res, '已找到货主待收货运单', '没有货主待收货运单数据');

    }

    //---------------------------------------后台管理------------------------------------------------------------------------------

    /*后台申请提现列表 可查用户*/
    public function adminWithdrawList($data): array
    {
        $re = Withdraw::orderBy('status','asc')->orderBy('create_time','desc');
        if($data['keywords']){
            $re->where(function($query) use ($data){
                $query->where('user_id', '=', $data['keywords']);});
        }
        $res = $re->paginate(10);
        return auto_return($res);

    }

    /*管理员 - 审核提现*/
    /*审核成功：修改为审核成功状态
    审核失败：修改为审核失败状态 + 解冻用户资金*/
    /*public function auditWithdraw($data): array
    {
         DB::beginTransaction();
        try{
            //修改提现记录状态
            $_where['id'] = $data['id'];
            $_where['status'] = 0;
            $withdrawInfo = Withdraw::where($_where)->first();
            if(!$withdrawInfo){
                return verify_err(null, '未找到相应的提现记录');
            }

            $saveData['status'] = $data['status'];
            $saveData['review_id'] = $data['review_id'];
            $saveData['review_info'] = json_encode($data['review_info']);
            $updateRes = Withdraw::where($_where)->update($saveData);

            if($data['status'] == 2){  //审核失败：解冻用户资金
                $unfreezeData['user_id'] = $withdrawInfo['user_id'];
                $unfreezeData['opposite_id'] = $data['review_id'];
                $unfreezeData['type'] = 'withdraw';
                $unfreezeData['obj_id'] = $data['id'];
                $unfreezeData['freeze_counts'] = 1;
                $unfreezeData['money'] = $withdrawInfo['money'];
                $unfreezeData['update_ip'] = $data['update_ip'];
                $unfreezeData['app_id'] = $withdrawInfo['app_id'];
                $unfreezeData['user_info'] = json_encode($withdrawInfo['user_info']);
                $unfreezeData['opposite_info'] = json_encode($data['review_info']);
                $unfreezeRes = (new \App\Services\Fund\FundAccount\FundAccountLogic())->unfreeze($unfreezeData);
                if($unfreezeRes['status'] != SUCCESS_STATUS){
                    return $unfreezeRes;
                }
            }
            // 提交事务
            DB::commit();
        }catch (\Exception $e) {
            // 回滚事务
             DB::rollback();
            return server_err(null, '数据库异常:' . $e->getMessage());
        }
        return auto_return($updateRes);
    }*/

    /*管理员 - 审核转账
      转让成功： 修改为转让成功状态 + 解冻用户资金 + 用户资金转让给平台(扣除用户资金)
      转让失败： 修改为转让失败状态 + 解冻用户资金
    */
    public function auditWithdraw($data): array
    {
        $_where['id'] = $data['id'];
        $_where['status'] = 0;
        $saveData['status'] = $data['status'];
        $saveData['review_id'] = $data['review_id'];
        $saveData['review_info'] = json_encode($data['review_info']);
        $saveData['update_time'] = time();
        //开启事务
        DB::beginTransaction();
        try{
            $withdrawInfo = Withdraw::where($_where)->first();
            if(!$withdrawInfo){
                return verify_err(null, '未找到相应的提现记录');
            }
            //修改状态
            $res = Withdraw::where($_where)->update($saveData);
            //解冻用户资金
            $unfreezeData['user_id'] = $withdrawInfo['user_id'];
            $unfreezeData['opposite_id'] = $data['review_id'];
            $unfreezeData['type'] = 'withdraw';
            $unfreezeData['obj_id'] = $data['id'];
            $unfreezeData['freeze_counts'] = 1;
            $unfreezeData['money'] = $withdrawInfo['money'];
            $unfreezeData['update_ip'] = $_SERVER['REMOTE_ADDR'];
            $unfreezeData['app_id'] = 22;
            $unfreezeData['user_info'] = json_encode($withdrawInfo['user_info']);
            $unfreezeData['opposite_info'] = json_encode($data['review_info']);
            $unfreezeRes = (new \App\Services\Fund\FundAccount\FundAccountLogic())->unfreeze($unfreezeData);
            if($unfreezeRes['status'] != SUCCESS_STATUS){
                return $unfreezeRes;
            }
            if($data['status'] == 1){ //后台转账成功给用户后： 用户资金支付给平台
                $transferData['user_id'] = $withdrawInfo['user_id'];
                $transferData['opposite_id'] = SYSTEM_ID;
                $transferData['money'] = $withdrawInfo['money'];
                $transferData['update_ip'] = $_SERVER['REMOTE_ADDR'];
                $transferData['app_id'] = 22;
                $transferData['user_info'] = json_encode($withdrawInfo['user_info']);
                $transferData['opposite_info'] = json_encode(['name'=>'system']);
                $transferData['remark'] = '用户提现成功';
                $transferRes = (new \App\Services\Fund\FundAccount\FundAccountLogic())->transfer($transferData);
                if($transferRes['status'] != SUCCESS_STATUS){
                    return $transferRes;
                }
            }
            // 提交事务
             DB::commit();
        }catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
            return server_err(null, '数据库异常:' . $e->getMessage());
        }
        return auto_return($res);
    }
}
